package com.gitee.mrj.aiboot.core.sf.generators.ui.widget;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.gitee.mrj.aiboot.annotation.config.KV;
import com.gitee.mrj.aiboot.annotation.config.sf.ui.widget.SFCascaderWidget;
import com.gitee.mrj.aiboot.core.sf.generators.FormDefinitionGenerator;
import com.gitee.mrj.aiboot.core.sf.generators.UIForm;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class SFCascaderWidgetGenerator implements FormDefinitionGenerator {
    @Override
    public void generate(UIForm root, Field field, UIForm node) {
        SFCascaderWidget cascaderWidget = AnnotatedElementUtils.findMergedAnnotation(field, SFCascaderWidget.class);
        generate(node, cascaderWidget);
    }

    private void generate(UIForm node, SFCascaderWidget cascaderWidget) {
        ObjectNode ui = node.getUi();
        ui.put("widget", "cascader");
        putString(ui, "placeholder", cascaderWidget.placeholder());
        ui.put("showSearch", cascaderWidget.showSearch());
        ui.put("allowClear", cascaderWidget.allowClear());
        putString(ui, "clearText", cascaderWidget.clearText());
        ui.put("showArrow", cascaderWidget.showArrow());
        ui.put("showInput", cascaderWidget.showInput());
        putString(ui, "menuClassName", cascaderWidget.menuClassName());
        if (ArrayUtils.isNotEmpty(cascaderWidget.menuStyle())) {
            ObjectNode objectNode = putObject(ui, "menuStyle");
            for (KV kv : cascaderWidget.menuStyle()) {
                objectNode.put(kv.key(), kv.value());
            }
        }
        putString(ui, "notFoundContent", cascaderWidget.notFoundContent());
        putString(ui, "columnClassName", cascaderWidget.columnClassName());
        ui.put("enableCache", cascaderWidget.enableCache());
        ui.put("expandTrigger", cascaderWidget.expandTrigger().type());
        ui.put("changeOnSelect", cascaderWidget.changeOnSelect());
        if (ArrayUtils.isNotEmpty(cascaderWidget.triggerAction())) {
            ArrayNode array = putArray(ui, "triggerAction");
            for (SFCascaderWidget.TriggerAction kv : cascaderWidget.triggerAction()) {
                array.add(kv.type());
            }
        }
        putString(ui, "valueProperty", cascaderWidget.valueProperty());
        putString(ui, "labelProperty", cascaderWidget.labelProperty());

    }


    @Override
    public Class[] supports() {
        return new Class[]{SFCascaderWidget.class};
    }
}
